package com.ww.springboot.boot.test;

import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;

public class AESUtils {
    private static Logger logger = LoggerFactory.getLogger(AESUtils.class);
    private static final String aesKey = "DvHmnDFn";  //密钥
    private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS7Padding";

    /**
     * 加密 ECB
     */
    public static String encryption(String content){
        if(aesKey == null) {return null; }
        try{
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            byte[] raw = aesKey.getBytes();
            // 密码
            DESKeySpec desKeySpec = new DESKeySpec(aesKey.getBytes());
            // 偏移量
            AlgorithmParameterSpec algorithmParameterSpec = new IvParameterSpec(aesKey.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generateSecret(desKeySpec), algorithmParameterSpec);
            byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
            String hexString = Hex.encodeHexString(encrypted);
            return hexString;
        } catch (Exception e) {
            logger.error("解密异常 ",e);
            e.printStackTrace();
        }
        return null;
    }
}
